<template>
  <div class="crud-container">
    <div><input v-model="prefix" placeholder="Filter prefix"></div>
  
    <select size="5" v-model="selected">
      <option v-for="name in filteredNames" :key="name">{{ name }}</option>
    </select>
  
    <label>Name: <input v-model="first"></label>
    <label>Surname: <input v-model="last"></label>
  
    <div class="buttons">
      <button @click="create">Create</button>
      <button @click="update">Update</button>
      <button @click="del">Delete</button>
    </div>
  </div>
</template>
<script setup lang="ts">
import {reactive,ref,computed,watch} from 'vue'
const names = reactive<string[]>(['Emil, Hans', 'Mustermann, Max', 'Tisch, Roman'])
const prefix = ref('')
const selected = ref('')
const first = ref('')
const last = ref('')
const filteredNames = computed(() => {
  return names.filter((name:string) => name.toLowerCase().startsWith(prefix.value.toLowerCase()))
})
watch(selected,(newValue,oldValue) => {
  console.log('selected',newValue,oldValue)
  const str = newValue.split(', ')
  first.value = str[0]
  last.value = str[1]
})
function create(){
  if(isValidate()){
    const name = first.value + ', '+last.value
    names.push(name)
    first.value=last.value=''
  }
}
function update(){
  if(selected.value && isValidate()){
    const idx = names.findIndex(name => selected.value === name)
    names[idx] = first.value +', '+last.value
    first.value=last.value=''
  }

}
function del(){
  if(selected.value){
    const idx = names.findIndex(name => selected.value === name)
    names.splice(idx,1)
    first.value=last.value=''
  }
}
function isValidate(){
  return first.value && last.value
}
</script>
<style scoped>
.crud-container{
  text-align:left;
}
* {
  font-size: inherit;
}

input {
  display: block;
  margin-bottom: 10px;
}

select {
  float: left;
  margin: 0 1em 1em 0;
  width: 14em;
}

.buttons {
  clear: both;
}

button + button {
  margin-left: 5px;
}
</style>